package com.tansun.tandata.controller;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import com.tansun.tandata.entity.LogInfoErro;
import com.tansun.tandata.utils.*;
import com.tansun.tandata.vo.LogInfoVO;
import com.tansun.tandata.vo.req.LogInfoSeachErroVo;
import com.tansun.tandata.vo.req.LogInfoSeachVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tansun.tandata.common.TandataServerEnum;
import com.tansun.tandata.entity.LogInfo;
import com.tansun.tandata.service.LogService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Api(value = "日志接口")
@RestController
@RequestMapping(value = "/sys/log")
public class LoginfoController extends ParentController {

    @Autowired
    private LogService logService;

    @ApiOperation(value = "查询日志", notes = "根据关键字查询日志")
    @RequestMapping(value = "/getLogInfoByKey", method = RequestMethod.POST)
    public ResponseBase<Map<String, Object>> getLogInfoByKey(@Valid @RequestBody LogInfoSeachVo logInfoSeachVo) {
        Map<String, Object> data = new HashMap<>();

        try {
            Page<Object> pageInfo = PageHelper.startPage(logInfoSeachVo.getPage(), logInfoSeachVo.getLimit(), true);
            List<LogInfo> logInfos = logService.getLogInfoByKey(logInfoSeachVo);
            data.put("total", pageInfo.getTotal());
            data.put("data", logInfos);
        } catch (Exception e) {
            e.printStackTrace();
            //保存错误日志
            LogInfoErro log = new LogInfoErro();
            log.setServerId(TandataServerEnum.One.getServerId());//tandata-sys
            log.setUrl(log.getServerId()+"/sys/log/getLogInfoByKey");
            log.setParamStr(JsonUtil.toJsonObjectString(logInfoSeachVo));
            log.setReqType(1);//POST
            log.setDesribe(e.getMessage());
            insertLogInfoErro(log);
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null); //系统错误
        }
        return setResultSuccess(data);

    }

    @ApiOperation(value = "日志信息插入", notes = "日志基本信息插入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "logInfoVO,", value = "日志信息", required = true, dataType = "UserVO"),
            @ApiImplicitParam(name = "bindingResult", value = "绑定结果验证", required = true, dataType = "BindingResult")
    })
    @RequestMapping(value = "/insertLogInfo", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ResponseBase insertLogInfo(@Valid @RequestBody LogInfoVO logInfoVO) {
        // 验证实体输入参数
/*		if (bindingResult.hasErrors()) {
			List<FieldErrorTip> fields = new ArrayList<>();
			FieldErrorTip fieldErrorTip;
			for (FieldError error : bindingResult.getFieldErrors()) {
				fieldErrorTip = new FieldErrorTip(error.getField(), error.getDefaultMessage());
				fields.add(fieldErrorTip);
			}
			return setResult(Constants.HTTP_RES_CODE_401, null, fields);
		}*/

        //初始化日志对象
        LogInfo logInfo = new LogInfo();
        logInfo.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        logInfo.setServerId(logInfoVO.getServerId());
        //获取
        logInfo.setSeverName(TandataServerEnum.map.get(logInfoVO.getServerId()));
        logInfo.setModular(logInfoVO.getModular());
        //获取操作名称
        logInfo.setOperation(logInfoVO.getOperation());
        logInfo.setComment(logInfoVO.getComment());
        //获取客户端IP
        //logInfo.setIpStr(IpUtils.getCustomerIp(request));
        //获取操作成功标识
        logInfo.setSuccess(logInfoVO.getSuccess());
        //设置详细日志外键
        logInfo.setBkey(logInfo.getBkey());
        logInfo.setCreateTime(new Date());
        try {
            logService.insertLogInfo(logInfo);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null); //系统错误
        }
        return setResultSuccess();
    }

    @ApiOperation(value = "查询提数日志详情", notes = "查询提数日志详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "bkey", value = "aaaa", required = false, dataType = "String"),
    })
    @RequestMapping(value = "getRaisnumLogDetal", method = RequestMethod.GET)
    public ResponseBase getRaisnumLogDetal(@RequestParam("bkey") String bkey) {
        String comment = null;
        try {
            comment = logService.selectLogInfoRaisnumById(bkey);
        } catch (Exception e) {
            e.printStackTrace();
            //保存错误日志
            LogInfoErro log = new LogInfoErro();
            log.setServerId(TandataServerEnum.One.getServerId());//tandata-sys
            log.setUrl(log.getServerId()+"/sys/log/getRaisnumLogDetal");
            log.setParamStr("bkey:"+bkey);
            log.setReqType(0);//GET
            log.setDesribe(e.getMessage());
            insertLogInfoErro(log);
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null); //系统错误
        }
        return setResultSuccess(comment);
    }

    @ApiOperation(value = "查询错误日志", notes = "查询错误日志")
    @RequestMapping(value = "/getLogInfoErroList", method = RequestMethod.POST)
    public ResponseBase<Map<String, Object>> getLogInfoErroList(@Valid @RequestBody LogInfoSeachErroVo logInfoSeachErroVo) {
        Map<String, Object> data = new HashMap<>();
        try {
            Page<Object> pageInfo = PageHelper.startPage(logInfoSeachErroVo.getPage(), logInfoSeachErroVo.getLimit(), true);
            List<LogInfoErro> logInfos = logService.getLogInfoErroList(logInfoSeachErroVo);
            data.put("total", pageInfo.getTotal());
            data.put("data", logInfos);
        } catch (Exception e) {
            e.printStackTrace();
            //保存错误日志
            LogInfoErro log = new LogInfoErro();
            log.setServerId(TandataServerEnum.One.getServerId());//tandata-sys
            log.setUrl(log.getServerId()+"/sys/log/getLogInfoErroList");
            log.setParamStr(JsonUtil.toJsonObjectString(logInfoSeachErroVo));
            log.setReqType(1);//POST
            log.setDesribe(e.getMessage());
            insertLogInfoErro(log);
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null); //系统错误
        }
        return setResultSuccess(data);

    }
    @RequestMapping(value = "/insertLogInfoErro", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ResponseBase insertLogInfoErro(@Valid @RequestBody LogInfoErro logInfoErro) {
        //获取
        logInfoErro.setSeverName(TandataServerEnum.map.get(logInfoErro.getServerId()));
        logInfoErro.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        logInfoErro.setCreateTime(new Date());
        try {
            logService.insertLogInfoErro(logInfoErro);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null); //系统错误
        }
        return setResultSuccess();
    }
}
